#include <GenericTypeDefs.h>
#include <string.h>

#include "Protocol.h"
#include "Switch.h"

#define PROTOCOL_HEADER "GET_SWITCHES"
#define PROTOCOL_RESPONSE_PARAM_TYPE PARAM_BINARY
#define PROTOCOL_RESPONSE_PARAM_LENGTH 3

static int GetSwitchesProtocol_matchesRequest(const BYTE* request, WORD requestLength);
static void GetSwitchesProtocol_buildResponse(const BYTE* request, WORD requestLength, BYTE* response, WORD* responseLength);

Protocol GetSwitchesProtocol = {
	GetSwitchesProtocol_matchesRequest,
	GetSwitchesProtocol_buildResponse
};

static int GetSwitchesProtocol_matchesRequest(const BYTE* request, WORD requestLength) {
	return memcmp(request, PROTOCOL_HEADER PROTOCOL_FOOTER, requestLength) == 0;
}

static void GetSwitchesProtocol_buildResponse(const BYTE* request, WORD requestLength, BYTE* response, WORD* responseLength) {
	SwitchFlags switchFlags = Switches.get();
	int length = 0;

	memcpy(response, PROTOCOL_HEADER PROTOCOL_PARAM_BEGIN, sizeof(PROTOCOL_HEADER PROTOCOL_PARAM_BEGIN) - 1);
	length += sizeof(PROTOCOL_HEADER PROTOCOL_PARAM_BEGIN) - 1;
	response += sizeof(PROTOCOL_HEADER PROTOCOL_PARAM_BEGIN) - 1;

	*response++ = switchFlags & SWITCH_1 ? '1' : '0';
	*response++ = switchFlags & SWITCH_2 ? '1' : '0';
	*response++ = switchFlags & SWITCH_3 ? '1' : '0';
	length += 3;

	memcpy(response, PROTOCOL_PARAM_END PROTOCOL_FOOTER, sizeof(PROTOCOL_PARAM_END PROTOCOL_FOOTER) - 1);
	response += sizeof(PROTOCOL_PARAM_END PROTOCOL_FOOTER) - 1;
	length += sizeof(PROTOCOL_PARAM_END PROTOCOL_FOOTER) - 1;

	*responseLength = length;
}
